package com.community.controller;

import com.community.service.NoticeService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/AdminDelete")
public class AdminDeleteNoticeController extends HttpServlet {
     private NoticeService noticeService = new NoticeService();

     @Override
     protected void doPost(HttpServletRequest request, HttpServletResponse response)
             throws ServletException, IOException {
          try {
               // 获取公告ID参数
               String idParam = request.getParameter("id");
               if (idParam == null || idParam.isEmpty()) {
                    //将一个键值对存储在当前 HTTP 请求对象的属性（Attribute）中
                    request.setAttribute("error", "公告ID不能为空");
                    request.getRequestDispatcher("error.jsp").forward(request, response);
                    return;
               }

               // 转换ID为整数
               int noticeId = Integer.parseInt(idParam);

               noticeService.deleteNotice(noticeId);

               request.getSession().setAttribute("message", "公告删除成功");
               response.sendRedirect(request.getContextPath() + "/AdminNotice");
          } catch (NumberFormatException e) {
               // 处理非法ID格式
               request.setAttribute("error", "无效的公告ID格式");
               request.getRequestDispatcher("error.jsp").forward(request, response);
          } catch (Exception e) {
               // 处理其他异常
               e.printStackTrace(); // 打印堆栈跟踪以便调试
               request.setAttribute("error", "删除公告时发生错误: " + e.getMessage());
               request.getRequestDispatcher("error.jsp").forward(request, response);
          }
     }
}